<template>
  <div>
    <Card shadow>
      <div class="search-con search-con-top">
        <ButtonGroup>
          <Button class="search-btn" type="primary" @click="handleModal()">
            <Icon type="search"/>&nbsp;&nbsp;新建用户
          </Button>
        </ButtonGroup>
      </div>
      <Table :columns="columns" :data="data" :loading="loading">
        <template slot="passed" slot-scope="{ row }">
          <Badge v-if="row.passed===1" status="success" text="正常"/>
          <Badge v-else-if="row.passed===2" status="success" text="锁定"/>
          <Badge v-else="" status="error" text="禁用"/>
        </template>
        <template  slot="action" slot-scope="{ row }">
          <a @click="handleModal(row)">编辑</a>&nbsp;
          <a @click="handleRemove(row)" v-if="row.is_system===0">删除</a>&nbsp;
        </template>
      </Table>
      <Page :total="pageInfo.total" :current="pageInfo.page" :page-size="pageInfo.limit" show-elevator show-sizer
            show-total
            @on-change="handlePage" @on-page-size-change='handlePageSize'></Page>
    </Card>
    <Modal v-model="modalVisible"
           :title="modalTitle"
           width="680"
           @on-ok="handleSubmit"
           @on-cancel="handleReset">
      <Form ref="userForm" :model="formItem" :rules="formItemRules" :label-width="100">
        <FormItem label="昵称" prop="nickname">
          <Input v-model="formItem.nickname" placeholder="请输入内容"></Input>
        </FormItem>
        <FormItem label="登录名" prop="name">
          <Input :disabled="formItem.id?true:false" v-model="formItem.name" placeholder="请输入内容"></Input>
        </FormItem>
        <FormItem label="登录密码" prop="password">
          <Input type="password" v-model="formItem.password"  placeholder="请输入内容"></Input>
        </FormItem>
        <FormItem label="再次确认密码" prop="passwordConfirm">
          <Input type="password" v-model="formItem.passwordConfirm" placeholder="请输入内容"></Input>
        </FormItem>
        <FormItem label="角色：" prop="role">
          <Select v-model="formItem.role_id" style="width:200px" v-if="formItem.is_system !== 1">
            <Option v-for="item in roleList" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
          <span v-else>内置管理员</span>
        </FormItem>
        <FormItem label="邮箱" prop="email">
          <Input v-model="formItem.email" placeholder="请输入内容"></Input>
        </FormItem>
        <FormItem label="手机号" prop="phone">
          <Input v-model="formItem.phone" placeholder="请输入内容"></Input>
        </FormItem>
        <FormItem label="状态">
          <RadioGroup v-model="formItem.passed">
            <Radio label="0">禁用</Radio>
            <Radio label="1">正常</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="描述">
          <Input v-model="formItem.desc" type="textarea" placeholder="请输入内容"></Input>
        </FormItem>
      </Form>

      <div slot="footer">
        <Button type="default" @click="handleReset">取消</Button>&nbsp;
        <Button type="primary" @click="handleSubmit">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { getUsers, storeUser, removeUser, getRoles } from '@/api/member'
export default {
  name: 'SystemUser',
  data () {
    const validatePassConfirm = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.formItem.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    const validateMobile = (rule, value, callback) => {
      var reg = /^1\d{10}$/
      if (value !== '' && !reg.test(value)) {
        callback(new Error('手机号码格式不正确'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      modalVisible: false,
      modalTitle: '',
      pageInfo: {
        total: 0,
        page: 1,
        limit: 10
      },
      formItemRules: {
        name: [
          { required: true, message: '登录名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '登录密码不能为空', trigger: 'blur' }
        ],
        passwordConfirm: [
          { validator: validatePassConfirm, trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ],
        phone: [
          { validator: validateMobile, trigger: 'blur' }
        ]
      },
      formItem: {
        id: '',
        name: '',
        role_id: 0,
        nickname: '',
        password: '',
        passwordConfirm: '',
        passed: 1,
        email: '',
        phone: '',
        desc: '',
        avatar: ''
      },
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '登录名称',
          key: 'name'
        },
        {
          title: '邮箱',
          key: 'email'
        },
        {
          title: '手机号',
          key: 'phone'
        },
        {
          title: '角色名',
          key: 'role_name'
        },
        {
          title: '昵称',
          key: 'nickname'
        },
        {
          title: '状态',
          slot: 'passed',
          key: 'passed'
        },
        {
          title: '描述',
          key: 'desc'
        },
        {
          title: '注册时间',
          key: 'created_at'
        },
        {
          title: '操作',
          slot: 'action',
          width: 125,
          fixed: 'right'
        }
      ],
      roleList: [],
      data: []
    }
  },
  methods: {
    handleReset () {
      const newData = {
        id: '',
        name: '',
        role_id: 0,
        nickname: '',
        passed: 1,
        email: '',
        password: '',
        passwordConfirm: '',
        phone: '',
        desc: '',
        avatar: ''
      }
      this.formItem = newData
      // 重置验证
      this.$refs['userForm'].resetFields()
      this.modalVisible = false
    },
    handleModal (data) {
      if (data) {
        this.modalTitle = '编辑用户'
        this.formItem = Object.assign({}, this.formItem, data)
      } else {
        this.modalTitle = '添加用户'
      }
      this.formItem.passed = this.formItem.passed + ''
      this.modalVisible = true
    },
    handleRemove (data) {
      if (data.is_system === 1) {
        this.$Message.error('系统用户，你无权限删除')
      } else {
        this.$Modal.confirm({
          title: '删除后将无法恢复,确定删除吗？',
          onOk: () => {
            removeUser({ id: data.id }).then(res => {
              this.handleSearch()
              if (res.code === 0) {
                this.pageInfo.page = 1
                res.data ? this.$Message.success('删除成功') : this.$Message.error('删除失败,权限不足')
              }
            })
          }
        })
      }
    },
    handleSubmit () {
      this.$refs['userForm'].validate((valid) => {
        if (valid) {
          storeUser(this.formItem).then(res => {
            if (res.code === 0) {
              this.$Message.success('保存成功')
              this.handleSearch()
              this.handleReset()
            } else if (res.code === 422) {
              for (var p in res.error) { this.$Message.error(res.error[p].join(',')) }
            }
          })
        }
      })
    },
    handleSearch () {
      this.loading = true
      getUsers({ page: this.pageInfo.page, limit: this.pageInfo.limit }).then(res => {
        this.data = res.data.data
        this.pageInfo.total = parseInt(res.data.total)
        this.loading = false
      })
      getRoles({ page: this.pageInfo.page, limit: this.pageInfo.limit }).then(res => {
        const root = {
          id: 0,
          name: '选择角色'
        }
        this.roleList = [root].concat(res.data.data)
        this.loading = false
      })
    },
    handlePage (current) {
      this.pageInfo.page = current
      this.handleSearch()
    },
    handlePageSize (size) {
      this.pageInfo.limit = size
      this.handleSearch()
    }
  },
  mounted: function () {
    this.handleSearch()
  }
}
</script>
